package com.haoshui.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haoshui.domain.ResponseResult;
import com.haoshui.domain.dto.UserAddDto;
import com.haoshui.domain.dto.UserDto;
import com.haoshui.domain.dto.UserStatusDto;
import com.haoshui.domain.dto.UserUpdateDto;
import com.haoshui.domain.entity.Role;
import com.haoshui.domain.entity.User;
import com.haoshui.domain.vo.MenuVo;
import com.haoshui.domain.vo.PageVo;
import com.haoshui.domain.vo.RouterVo;
import com.haoshui.domain.vo.UserRoleFindVo;
import com.haoshui.enums.AppHttpCodeEnum;
import com.haoshui.service.*;
import com.haoshui.utils.BeanCopyUitls;
import com.haoshui.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class    UserController {

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    /**
     * 登录校验
     * @param userDto
     * @return
     */
    @PostMapping("/user/login")
    public ResponseResult userLogin(@RequestBody UserDto userDto){
        User user = BeanCopyUitls.copyBean(userDto, User.class);
        return sysLoginService.login(user);
    }


    /**
     * 获取登录用户信息
     * @return
     */
    @GetMapping("/getInfo")
    public ResponseResult getInfo(){
        return sysLoginService.getInfo();
    }


    /**
     * 获取用户对应权限的菜单
     * @return
     */
    @GetMapping("/getRouters")
    public ResponseResult getRouters(){
        //获取用户Id
        Long userId = SecurityUtils.getUserId();

        //查询menu。获取menuTree
        List<MenuVo> menus= menuService.selectMenuTreeByUserId(userId);

        RouterVo routerVo = new RouterVo(menus);

        return ResponseResult.okResult(routerVo);
    }


    /**
     * 用户退出登录
     * @return
     */
    @PostMapping("/user/logout")
    public ResponseResult userLogout(){
        return sysLoginService.logout();
    }


    /**
     * 页查询所有用户，有可能有依靠信息模糊查询
     * @param pageNum
     * @param pageSize
     * @param userName
     * @param phonenumber
     * @param status
     * @return
     */
    @GetMapping("/system/user/list")
    @PreAuthorize("@ps.hasPermission('system:user:list')")
    public ResponseResult userList(Integer pageNum, Integer pageSize, String userName, String phonenumber, String status){
        //查找用户
        Page<User> page =  userService.PageUserByCondition(pageNum, pageSize, userName, phonenumber, status);

        //封装Vo
        PageVo pageVo = new PageVo(page.getRecords(), page.getTotal());

        return ResponseResult.okResult(pageVo);
    }


    /**
     * 添加用户
     * @param userAddDto
     * @return
     */
    @PostMapping("/system/user")
    @PreAuthorize("@ps.hasPermission('system:user:add')")
    public ResponseResult addUser(@RequestBody UserAddDto userAddDto){
        //用户名不能重复
        if (userService.hasName(userAddDto.getUserName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_EXIST);
        }

        //用户昵称不能重复
        if(userService.hasNickName(userAddDto.getNickName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NICKNAME_EXIST);
        }

        //用户手机号不能重复
        if(userService.hasPhoneNumber(userAddDto.getPhonenumber())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }

        //用户邮箱不能重复
        if(userService.hasEmail(userAddDto.getEmail())){
            return ResponseResult.errorResult(AppHttpCodeEnum.EMAIL_EXIST);
        }

        //添加user表
        User user = BeanCopyUitls.copyBean(userAddDto, User.class);
        boolean save =  userService.addUser(user);

        //添加到userRole表
        boolean add =   userRoleService.addUserRole(user.getId(), userAddDto.getRoleIds());

        if(save && add){
            return ResponseResult.okResult();
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.INSERT_FAILED);
        }

    }


    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/system/user/{id}")
    @PreAuthorize("@ps.hasPermission('system:user:remove')")
    public ResponseResult deleteUser(@PathVariable("id") Long id){
        boolean b = userService.removeById(id);

        if(b){
            return ResponseResult.okResult();
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FAILED);
        }
    }


    /**
     * 修改用户信息，之前需要查询用户信息
     * @param id
     * @return
     */
    @GetMapping("/system/user/{id}")
    @PreAuthorize("@ps.hasPermission('system:user:edit')")
    public ResponseResult findUser(@PathVariable("id") Long id){
        //查找用户信息
        User user = userService.getById(id);

        // TODO 用户封装Vo

        //查找用户所关联的role
        List<Long> roleIds =  userRoleService.getRoleIdsByUserId(id);

        //获取全部的roles
        List<Role> roles =  roleService.getAllRoles();

        //封装结果
        UserRoleFindVo userRoleFindVo = new UserRoleFindVo(roleIds, roles, user);

        return ResponseResult.okResult(userRoleFindVo);

    }


    /**
     * 更新用户信息
     * @param userUpdateDto
     * @return
     */
    @PutMapping("/system/user")
    @PreAuthorize("@ps.hasPermission('system:user:edit')")
    public ResponseResult updateUser(@RequestBody UserUpdateDto userUpdateDto){
        //封装user
        User user = BeanCopyUitls.copyBean(userUpdateDto, User.class);

        //更新用户
        boolean b = userService.updateById(user);

        //更新userRole
        boolean update =  userRoleService.updateUserRole(user.getId(), userUpdateDto.getRoleIds());

        if(update && b){
            return ResponseResult.okResult();
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_FAILED);
        }
    }


    /**
     * 更改用户的状态信息
     * @param statusDto
     * @return
     */
    @PutMapping("/system/user/changeStatus")
    @PreAuthorize("@ps.hasPermission('system:user:list')")
    public ResponseResult updateUserStatus(@RequestBody UserStatusDto statusDto){
        //更新用户的状态
        boolean b =  userService.updateUserStatus(statusDto.getUserId(), statusDto.getStatus());

        if(b) {
            return ResponseResult.okResult();
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_FAILED);
        }
    }

}
